package com.fanketly.funacg2

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.lifecycleScope
import com.fanketly.funacg2.data.network.RetrofitNetwork
import com.fanketly.funacg2.ui.navigation.DrawerDestination
import com.fanketly.funacg2.ui.screen.NavGraphs
import com.fanketly.funacg2.ui.screen.appCurrentDestinationAsState
import com.fanketly.funacg2.ui.screen.destinations.DetailDestination
import com.fanketly.funacg2.ui.screen.destinations.FavouriteScreenDestination
import com.fanketly.funacg2.ui.screen.destinations.TagsScreenDestination
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.viewmodels.FavouriteViewModel
import com.fanketly.funacg2.ui.viewmodels.GlobalStates
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.MusicViewModel
import com.fanketly.funacg2.ui.viewmodels.TagViewModel
import com.fanketly.funacg2.ui.viewmodels.state.GlobalState
import com.fanketly.funacg2.utils.ToastUtils
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.manager.PlaybackStage
import com.ramcosta.composedestinations.DestinationsNavHost
import com.ramcosta.composedestinations.navigation.dependency
import com.ramcosta.composedestinations.navigation.navigate
import com.ramcosta.composedestinations.navigation.popUpTo
import com.ramcosta.composedestinations.rememberNavHostEngine
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val musicViewModel by viewModels<MusicViewModel>()
    private val homeViewModel: HomeViewModel by viewModels()


    @Inject
    lateinit var retrofitNetwork: RetrofitNetwork

    @Inject
    lateinit var globalStates: GlobalStates

    private val drawerList by lazy {
        mutableListOf(
            DrawerDestination.Home,
            DrawerDestination.Search,
            DrawerDestination.Favourite,
            DrawerDestination.History,
            DrawerDestination.Setting,
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            ToastUtils.shortToast(getString(R.string.get_best_server))
            with(retrofitNetwork) {
                getBestServer {
                    setView()
                }
            }
        }
    }


    private fun setView() {
        if (!App.sIsAllAges) drawerList.add(2, DrawerDestination.Tags)
        val drawerDestinationList = drawerList.map { it.direction }
        setContent {
            FunACG2Theme(dynamicColor = false) {
                //侧滑
                val drawerState = rememberDrawerState(DrawerValue.Closed)
                val scope = rememberCoroutineScope()
                var selectedItem by remember { mutableIntStateOf(0) }
                //导航
                val rememberNavHostEngine = rememberNavHostEngine()
                val rememberNavController = rememberNavHostEngine.rememberNavController()
                val currentDestination = rememberNavController.appCurrentDestinationAsState().value
                    ?: NavGraphs.root.startRoute
                ModalNavigationDrawer(drawerState = drawerState,
                    gesturesEnabled = currentDestination in drawerDestinationList,
                    modifier = Modifier.background(MaterialTheme.colorScheme.background),
                    drawerContent = {
                        ModalDrawerSheet {
                            Spacer(Modifier.height(12.dp))
                            drawerList.forEachIndexed { index, item ->
                                NavigationDrawerItem(
                                    icon = {
                                        Icon(
                                            item.icon,
                                            contentDescription = null
                                        )
                                    },
                                    label = { Text(stringResource(id = item.label)) },
                                    selected = index == selectedItem,
                                    onClick = {
                                        if (selectedItem == index) return@NavigationDrawerItem
                                        scope.launch {
                                            selectedItem = index
                                            drawerState.close()
                                            rememberNavController.navigate(item.direction) {
                                                popUpTo(NavGraphs.root) {
                                                    saveState = true
                                                }
                                                launchSingleTop = true
                                                restoreState = true
                                            }
                                        }
                                    },
                                    modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
                                )
                            }
                        }
                    }) {
                    DestinationsNavHost(navGraph = NavGraphs.root,
                        engine = rememberNavHostEngine,
                        navController = rememberNavController,
                        dependenciesContainerBuilder = {
                            dependency(homeViewModel)
                            dependency(musicViewModel)
                            dependency(TagsScreenDestination) {
                                hiltViewModel<TagViewModel>(this@MainActivity)
                            }
                            dependency(DetailDestination) {
                                hiltViewModel<FavouriteViewModel>(this@MainActivity)
                            }
                            dependency(FavouriteScreenDestination) {
                                hiltViewModel<FavouriteViewModel>(this@MainActivity)
                            }
//                                    dependency(DetailDestination, dependencyProvider = {
//                                        {
//                                            destinationsNavigator.popBackStack()
//                                            Unit
//                                        }
//                                    })
                        })
                }

                LaunchedEffect(key1 = globalStates.globalUiState, block = {
                    if (globalStates.globalUiState is GlobalState.ToDetail) {
//                        Log.i("TAG", "setView: "+globalStates.globalUiState)
                        rememberNavController.navigate(DetailDestination)
                    }
                })
                GlobalState(
                    globalStates.globalUiState,
//                    toDetail = { rememberNavController.navigate(DetailDestination) },
                    openDrawer = { scope.launch { drawerState.open() } },
                    onClose = globalStates::setStateClose,
                    onReload = homeViewModel::reload
                )
            }
        }
    }

    override fun onStart() {
        super.onStart()
        App.sServiceConnect.observe(this) {
            if (it) {
                setPlaybackState()
            }
        }
    }

    private fun setPlaybackState() {
        StarrySky.with().playbackState().observe(this) { stage ->
            musicViewModel.apply {
                when (stage.stage) {
                    PlaybackStage.ERROR -> {
                        ToastUtils.shortToast("播放错误")
                    }

                    PlaybackStage.PLAYING -> {
                        _isPlaying.value = true
                        stage.songInfo?.let {
                            _audioInfo.value = it
                            _audioAllTime.value = (StarrySky.with().getDuration() / 1000).toInt()
                        }
                        setOnPlayProgressListener()
                    }

                    PlaybackStage.PAUSE -> {
                        _isPlaying.value = false
                    }

                    PlaybackStage.IDLE -> {
                        _isPlaying.value = false
                        _audioProcess.value = 0
                    }
                }
            }
        }
    }

}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun GlobalState(
    state: GlobalState,
//    toDetail: () -> Unit,
    openDrawer: () -> Unit,
    onClose: () -> Unit,
    onReload: () -> Unit,
) {
    Log.i("TAG", "GlobalState: $state")
    when (state) {
        is GlobalState.ShowToast -> {
            ToastUtils.shortToast(state.message)
            onClose()
        }

        GlobalState.Loading -> {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .combinedClickable(indication = null,
                        interactionSource = remember { MutableInteractionSource() },
                        role = Role.Image,
                        onClick = { }), contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }

        GlobalState.NotAuthorization -> {
            AlertDialog(
                onDismissRequest = { onClose() },
                confirmButton = {
                    TextButton(onClick = { onReload() }) {
                        Text(text = stringResource(id = R.string.confirm))
                    }
                },
                text = { Text(text = stringResource(id = R.string.not_authorization)) })
        }

        GlobalState.Close -> {
        }

        is GlobalState.ToDetail -> {
//            toDetail()
        }

        GlobalState.OpenDrawer -> {
            openDrawer()
            onClose()
        }
    }
}


@Preview
@Composable
private fun Preview() {
    FunACG2Theme {
        Surface {
//            GlobalState(state = GlobalState.NotAuthorization, onClose = { }) {
//
//            }
        }
    }
}
